<template>
  <div class="goods-detail" @click.stop>
    <div class="top-title">
      <span class="back" @click.stop="goBack">
        <i class="iconfont icon-arrow-left"></i>
      </span>
    </div>
    <div class="article-detail-wrapper">
      <div class="top-img-wrapper">
        <div class="top-img-inner-wrapper" :style="{ backgroundImage: getTopImgBgImg }">
        </div>
      </div>
      <div class="mall">
        <span>{{ article_mall }}</span><span>{{ last_update_time }}</span><span>{{ article_referrals }}</span>
      </div>
      <div class="title">
        {{goodsDetailItem.article_title || articleDescObj.article_mall}}
      </div>
      <div class="price">
        {{goodsDetailItem.article_price}}
      </div>
      <div class="arrive-button-wrapper">
        <a target="_blank" :href="articleLink">
          <span class="arrive-button">直达链接</span>
        </a>
      </div>
      <div class="content">
        <div class="content-title">{{articleDescObj.title || '' }}</div>
        <div class="content-desc">{{articleDescObj.desc || ''}}</div>
      </div>
      <div class="tags">
        <span class="tag border" v-for="(tag, index) in tagsArr" :key="index"> {{tag.tagText}}</span>
      </div>
      <a target="_blank" href="https://m.smzdm.com/app/android.html?is_detail=1">
        <div class="arrive-full-button">打开APP，查看更多好价</div>
      </a>
    </div>
    <page-splite></page-splite>
    <div class="evaluate">
      <div class="title-text">我觉得这个商品：</div>
      <a>
      <div class="i-wrapper border left" @click.stop="evaluateGoods(1)">
        <i class="z-icon-zhi"></i><span class="text">{{articleDescObj.worth || 0}}</span>
      </div>
      </a>
      <a>
      <div class="i-wrapper border" @click.stop="evaluateGoods(-1)">
        <i class="z-icon-not"></i><span class="text">{{articleDescObj.unWorth || 0}}</span>
      </div>
      </a>
    </div>
    <page-splite v-show="this.articleDescObj && this.articleDescObj.commentsArr && this.articleDescObj.commentsArr.length > 0">
      <div class="split-cls">
        <i class="weui icon-comments-s"></i> 全部评论
      </div>
    </page-splite>
    <comments-m v-if="this.articleDescObj && this.articleDescObj.commentsArr && this.articleDescObj.commentsArr.length > 0" :data="this.articleDescObj.commentsArr"></comments-m>
    <!--
    <ul class="comments-wrapper" v-show="this.articleDescObj && this.articleDescObj.commentsArr && this.articleDescObj.commentsArr.length > 0">
      <li v-for="(item, index) in this.articleDescObj.commentsArr" :key="index" class="comments border-bottom">
        <div class="avatar">
          <img :src="getImgSrc(item.avatarSrc)" width="35px" height="35px">
        </div>
        <div class="comments-info">
          <div class="comments-top">
            <div class="nickname">{{item.nickname}}</div>
            <div class="time">{{item.time}}</div>
            <div class="zan-wrapper">
              <span class="zan">{{item.zan}}</span>
              <span><i class="weui icon-thumb-up-o"></i></span>
            </div>
          </div>
          <p class="comments-content" v-html="item.commentContent"></p>
        </div>
      </li>
      <li class="open-app">
        <a target="_blank" href="https://m.smzdm.com/app/?is_detail=1">打开App 参与讨论</a>
      </li>
    </ul>
    -->
    <page-splite >
      <div class="split-cls">
        <i class="weui icon-hot-title"></i> 热门推荐
      </div>
    </page-splite>
    <article-list :articles="hotRecommentList" :showLabelTitle="showLabelTitle" @selectItem="selectArticle" ></article-list>
    <div class="scroll-loading-wrapper">
      <scroll-loading v-show="loadingFlag && hasLoadingIds.length > 19"></scroll-loading>
    </div>
    <div class="bottom-link-wrapper">
      <div class="zhi text">
        <span class="i-wrapper" data-text="zhi" @click.prevent.stop="iconClick"><i class="weui icon-zhi"></i></span><span>{{articleDescObj.worth || ''}}</span>
      </div>
      <div class="favorite text">
        <span class="i-wrapper" data-text="favorite" @click.prevent.stop="iconClick"><i class="weui icon-star-o"></i></span><span>{{articleDescObj.favorite || ''}}</span>
      </div>
      <div class="share text">
        <span class="i-wrapper" data-text="share" @click.prevent.stop="iconClick"><i class="weui icon-share-o"></i></span><span>分享</span>
      </div>
      <div class="comments text">
        <span class="i-wrapper" data-text="comments" @click.prevent.stop="iconClick"><i class="weui icon-comments-o"></i></span><span>{{articleDescObj.comments || ''}}</span>
      </div>
      <div class="arrive-link">
        <div class="half-circle">
        </div>
        <a target="_blank" :href="articleLink">
          <span>直达链接</span>
        </a>
      </div>
    </div>
    <div class="scroll-top-wrapper" v-show="this.currentScrollT > 230">
      <scroll-top></scroll-top>
    </div>
    <div class="fullscreen-loading-wrapper" v-show="this.loadingDescFlag">
      <div class="fullscreen-loading-inner">
        <div class="fs-loading">
          <fullscreen-loading></fullscreen-loading>
        </div>
      </div>
    </div>
    <top-tip ref="topTip" class="clsTopTip">
      <div class="top-tip-inner">您已经点过值了</div>
    </top-tip>
  </div>
</template>

<script type="text/ecmascript-6">
import { mapGetters, mapActions } from 'vuex'
import { scrollMixin } from 'common/js/mixin'
import { getGoodsDetail } from 'api/goodsDetail'
import { getHotRecommend } from 'api/hotRecommend'
import PageSplite from 'base/page-splite/page-splite'
import ArticleList from 'components/article-list/article-list'
import ScrollLoading from 'base/scroll-loading/scroll-loading'
import ScrollTop from 'base/scroll-top/scroll-top'
import GotoHome from 'base/goto-home/goto-home'
import { getData } from 'common/js/dom'
import FullscreenLoading from 'base/fullscreen-loading/fullscreen-loading'
import { getImgSrc, filterIds, filterList, genArrOfIds } from 'common/js/tools'
import TopTip from 'base/top-tip/top-tip'
import CommentsM from 'components/comments-m/comments-m'

export default {
  name: 'goods-detail',
  mixins: [ scrollMixin ],
  components: {
    PageSplite,
    ArticleList,
    ScrollLoading,
    ScrollTop,
    FullscreenLoading,
    GotoHome,
    TopTip,
    CommentsM
  },
  data () {
    return {
      showFullscreenLoading: true,
      showLabelTitle: false,
      hasLoadingIds: [],
      hotRecommentList: [],
      loadingFlag: false,
      loadingDescFlag: false,
      articleDescObj: {},
      mountedTimestamp: new Date().getTime()
    }
  },
  computed: {
    articleLink () {
      let articleLink = this.goodsDetailItem.article_link || this.goodsDetailItem.article_url
      if (articleLink && articleLink.indexOf('http') > -1) {
        return articleLink
      } else if (articleLink) {
        return 'https:' + articleLink
      }
    },
    tagsArr () {
      let tmpArr = []
      let articleObj = this.goodsDetailItem
      if (!articleObj) return
      if (articleObj.article_category) {
        tmpArr.push({
          tagText: '分类：' + articleObj.article_category.title
        })
      }
      if (articleObj.article_tese_tags && articleObj.article_tese_tags.length > 0) {
        let tmpStr = ''
        articleObj.article_tese_tags.forEach((item) => {
          tmpStr += item.name
        })
        tmpArr.push({
          tagText: '话题：' + tmpStr
        })
      }
      if (articleObj.article_mall) {
        tmpArr.push({
          tagText: '商城：' + articleObj.article_mall
        })
      }
      if (articleObj.gtm) {
        tmpArr.push({
          tagText: '品牌：' + articleObj.gtm.brand
        })
      }
      return tmpArr
    },
    article_mall () {
      return this.goodsDetailItem.article_mall
    },
    last_update_time () {
      // console.log('last_update_time computed')
      let reStr = this.articleDescObj.last_update_time ? this.articleDescObj.last_update_time : this.goodsDetailItem.last_update_time ? this.goodsDetailItem.last_update_time : ''
      return '| ' + reStr
    },
    article_referrals () {
      let reStr = this.articleDescObj.article_referrals ? this.articleDescObj.article_referrals : this.goodsDetailItem.article_referrals ? this.goodsDetailItem.article_referrals : ''
      return '| ' + reStr
    },
    // mallinfo () {
    //   let reStr = ''
    //   if (this.goodsDetailItem.article_id) {
    //     if (this.goodsDetailItem.article_mall) {
    //       reStr += this.goodsDetailItem.article_mall + ' | '
    //     }
    //     if (this.goodsDetailItem.last_update_time) {
    //       reStr += this.goodsDetailItem.last_update_time + ' | '
    //     }
    //     if (this.goodsDetailItem.article_referrals) {
    //       reStr += '爆料人：' + this.goodsDetailItem.article_referrals
    //     }
    //   }
    //   return reStr
    // },
    ...mapGetters({
      goodsDetailItem: 'goodsDetailItem',
      visitedList: 'visitedList',
      evaluatedList: 'evaluatedList'
    }),
    getTopImgBgImg () {
      // if (!this.goodsDetailItem.article_pic) return
      // let regexp = /(gif|jpg|jpeg|bmp|png)(\S+).\1/
      // let articlePic = this.goodsDetailItem.article_pic
      // if (articlePic && articlePic.length > 0) {
      //   let match = articlePic.match(regexp)
      //   if (!match) return
      //   if (match[2]) {
      //     let lastIndexOfMatch = articlePic.lastIndexOf(match[2])
      //     articlePic = articlePic.replace(match[2], '_d480', lastIndexOfMatch)
      //   }
      // }
      return 'url("' + getImgSrc(this.goodsDetailItem.article_pic) + '")'
    }
  },
  methods: {
    getImgSrc (p) {
      return getImgSrc(p)
    },
    showTopTip () {
      if (this.topTipTimer) {
        clearTimeout(this.topTipTimer)
        this.$refs.topTip.hide()
      }
      this.$refs.topTip.show()
      this.topTipTimer = setTimeout(() => {
        this.$refs.topTip.hide()
      }, 4000)
    },
    checkHasEvaluated () {
      return (this.evaluatedList.indexOf(this.goodsDetailItem.article_id) > -1)
    },
    evaluateGoods (rating) {
      if (this.checkHasEvaluated()) {
        this.showTopTip()
      } else {
        if (rating === 1) {
          this.articleDescObj.worth = parseInt(this.articleDescObj.worth) + 1
        }
        if (rating === -1) {
          this.articleDescObj.unWorth = parseInt(this.articleDescObj.unWorth) + 1
        }
        this.pushToEvaluated(this.goodsDetailItem.article_id)
        // evaluateGoods(this.goodsDetailItem.article_id, (this.goodsDetailItem.article_channel_id || this.goodsDetailItem.channel_id), rating).then((resp) => {
        //   console.log('evaluateGoods resp:')
        //   console.log(resp)
        // }).catch((e) => {
        //   console.log('evaluateGoods error:')
        //   console.log(e)
        // })
      }
    },
    ...mapActions({
      pushToVisitedList: 'pushToVisitedList',
      pushToEvaluated: 'pushToEvaluated'
    }),
    selectArticle (article) {
      // console.log('select article ')
      // console.log(article)
      // this.routeToGoodsDetailPage(article)
      // this.routeToGoodsDetailAction(article)
      // this.routeToGoodsDetailPage(article)
      this.$store.commit('SET_GOODS_DETAIL_ITEM', article)
      // console.log()
      if (this.$route.name !== 'goodsDetail') {
        this.$router.push('/goodsdetail/' + article.article_id)
      }
    },
    iconClick (e) {
      let iText = getData(e.target, 'text')
      if (iText === 'zhi') {
        this.evaluateGoods(1)
      }
    },
    getMoreList () {
      console.log('goods-detail getMoreList:')
      this.getHotRecommendData(this.goodsDetailItem)
    },
    goBack () {
      // console.log('go back')
      this.$router.back()
    },
    getHotRecommendData (article) {
      if (this.loadingFlag) return // 如果数据正在加载的话，不进行重复加载
      this.loadingFlag = true
      getHotRecommend(this.mountedTimestamp, article.article_id, (article.article_channel_id || article.channel_id)).then((resp) => {
        if (resp.message === 1) {
          // this.hotRecommentList = resp.data
          let newData = resp.data
          let arrIds = genArrOfIds(newData)
          let newValidIds = filterIds(arrIds, this.hasLoadingIds)
          let validItems = filterList(newValidIds, newData)
          this.hotRecommentList = this.hotRecommentList.concat(validItems)
          this.hasLoadingIds = this.hasLoadingIds.concat(newValidIds)
          if (!validItems.length) {
            this.resetMountedTimestamp()
          }
          console.log('详情页，hot-recommend 新加载了(' + validItems.length + ')条数据')
          this.loadingFlag = false
        }
      }).catch(() => {
        this.loadingFlag = false
      })
    },
    getGoodsDetailData (article) {
      this.loadingDescFlag = true
      getGoodsDetail(article.article_id).then((resp) => {
        if (resp.message === 1) {
          this.articleDescObj = resp.data
        }
        this.loadingDescFlag = false
      }).catch((e) => {
        this.loadingDescFlag = false
        this.articleDescObj = {
          title: this.goodsDetailItem.article_content,
          desc: ''
        }
        console.log(e)
      })
    },
    // loadInitData () {
    //   if (!this.goodsDetailItem.article_id) return
    //   let newVal = this.goodsDetailItem
    //   if (newVal.article_id) {
    //     console.log('to invoke api getGoodsDetail')
    //     this.getGoodsDetailData(newVal)
    //   }
    //   let channelId = newVal.article_channel_id || newVal.channel_id
    //   // console.log('loadInitData channelId' + channelId)
    //   if (newVal.article_id && channelId) {
    //     console.log('to invoke api getHotRecommend')
    //     this.getHotRecommendData(newVal)
    //   }
    //   this.pushToVisitedList(this.goodsDetailItem.article_id)
    // },
    reloadInitData (newVal, oldVal) {
      if (newVal.article_id) {
        this.getGoodsDetailData(newVal)
      }
      let channelId = newVal.article_channel_id || newVal.channel_id
      let channelIdOld = oldVal.article_channel_id || oldVal.channel_id
      // console.log('channelId, channelIdOld: ', channelId, '-', channelIdOld)
      if (channelId !== channelIdOld) {
        this.hasLoadingIds = []
        this.hotRecommentList = []
        this.getHotRecommendData(newVal)
      }
      // this.pushToVisitedList(newVal.article_id)
    }
  },
  mounted () {
    // console.log(this.goodsDetailItem)
    if (!this.goodsDetailItem || !this.goodsDetailItem['article_id']) {
      this.$router.push('/homepage')
    }
    this.reloadInitData(this.goodsDetailItem, {})
    this.pushToVisitedList(this.goodsDetailItem.article_id)
    // this.$store.commit('SET_SEARCH_TITLE', false)
    // this.$store.commit('SET_TABS_STATE', false)
    // this.loadInitData()
  },
  activated () {
    this.$store.commit('SET_SEARCH_TITLE', false)
    this.$store.commit('SET_TABS_STATE', false)
    setTimeout(() => {
      window.scrollTo(0, 0)
    }, 100)
  },
  watch: {
    goodsDetailItem (newObj, oldObj) {
      // console.log('watch goodsDetailItem:')
      // console.log(newObj)
      // console.log(oldObj)
      setTimeout(() => {
        window.scrollTo(0, 0)
      }, 100)
      // if (newObj.article_id === oldObj.article_id) return
      this.reloadInitData(newObj, oldObj)
      this.pushToVisitedList(newObj.article_id)
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~common/stylus/mixin'
@import '~common/stylus/variable'

.goods-detail
  position: relative
  padding-bottom: 40px
  .top-title
    position: fixed
    top: 10px
    left: 10px
    color: #fff
    z-index: 2
    width: 30px
    height: 30px
    border-radius: 50%
    text-align: center
    background: rgba(100, 100, 100, 0.5)
    .back
      extend-click()
      line-height: 30px
      font-size: 22px
      .icon-arrow-left
        font-size: 22px
  .article-detail-wrapper
    padding: 0 10px
    .top-img-wrapper
      width: 100%
      text-align: center
      margin-top: 5px
      .top-img-inner-wrapper
        display: inline-block
        width: 50%
        height: 0
        padding-bottom: 50%
        background-repeat: no-repeat
        background-size: cover
    .mall
      color: #888888
      font-size: $font-size-small
      line-height: 14px
      margin-bottom: 14px
    .title
      font-size: 18px
      line-height: 22px
      font-weight: 700
      margin-bottom: 8px
    .price
      font-size: 16px
      line-height: 20px
      font-weight: 700
      color: #F04848
      margin-bottom: 14px
    .arrive-button-wrapper
      margin-bottom: 14px
      .arrive-button
        display: inline-block
        padding: 4px 8px
        font-size: 16px
        line-height: 16px
        background: #F3695A
        color: #fff
        border-radius: 2px
    .content
      margin-bottom: 14px
      .content-title
        font-size: 18px
        line-height: 26px
        margin-bottom: 14px
        font-weight: 700
        // >>> strong  // 样式穿透
        //   font-weight: 700
      .content-desc
        font-size: 16px
        line-height: 20px
    .tags
      line-height: 28px
      margin-bottom: 16px
      .tag
        display: inline-block
        padding: 5px
        border-radius: 1px
        font-size: $font-size-small
        line-height: $font-size-small
        background: #eaeaea
        margin-right: 10px
    .arrive-full-button
      text-align:center
      padding: 8px 8px
      font-size: 16px
      line-height: 16px
      background: #F04848
      color: #fff
      border-radius: 2px
      margin-bottom: 16px

  .evaluate
    text-align: center
    padding: 12px
    .title-text
      text-align: left
      margin-bottom: 10px
      font-size: 14px
    .i-wrapper
      display: inline-block
      font-size: 0
      border-radius: 2px
      vertical-align: middle
      padding: 5px 0px 5px 8px
      &.left
        margin-right: 20px
      .text
        display: inline-block
        font-size: 16px
        line-height: 20px
        padding: 0px 20px
        vertical-align: middle
      .z-icon-zhi, .z-icon-not
        display: inline-block
        vertical-align: middle
        font-size: 0
        width: 20px
        height: 20px
  .split-cls
    font-size: 14px
    font-weight: 600
    padding: 3px 3px 3px 10px
    i
      color: #F04848
      vertical-align: middle
  .scroll-loading-wrapper
    margin-bottom: 40px
  .bottom-link-wrapper
    position: fixed
    display: flex
    width: 100%
    left: 0
    bottom: 0
    height: 40px
    background: #FBFBFB
    .text
      flex: 1
      text-align: center
      line-height: 40px
      font-size: 12px
      z-index: 2
      .i-wrapper
        vertical-align: bottom
        extend-click()
        i
          color: #F04848
      span
        vertical-align: bottom
        padding: 0 4px
    .arrive-link
      flex: 2
      background: #F04848
      line-height: 40px
      position:relative
      span
        padding-left: 30px
        font-size: 16px
        color: #fff
        font-weight: 600
        extend-click()
        cursor: pointer
      .half-circle
        position: absolute
        top: 5px
        width: 40px
        height: 40px
        transform: translate3d(-30px, -5px, 0px)
        border-radius: 50%
        background: #FBFBFB
  .scroll-top-wrapper
    position: fixed
    right: 5px
    bottom: 180px
  .fullscreen-loading-wrapper
    z-index: 10
    position: fixed
    left: 0
    top: 0
    right: 0
    bottom: 0
    background: #FFFFFE
    .fullscreen-loading-inner
      position: relative
      width: 100%
      height: 100%
      .fs-loading
        position: absolute
        width: 100%
        top: 50%
        text-align: center
        transform: translateY(-50%)
/*
  .comments-wrapper
    .comments
      display: flex
      padding: 10px
      .avatar
        flex: 0 0 35px
        width: 35px
        text-align: center
        img
          display: inline-block
      .comments-info
        flex: 1
        padding-left: 16px
        .comments-top
          position: relative
          margin-bottom: 16px
          .nickname
            font-size: 16px
            line-height: 24px
            font-weight: 600
            color: #000
          .time
            font-size: 10px
            line-height: 14px
            color: #888888
          .zan-wrapper
            position: absolute
            right: 0
            top: 2px
            span
              padding: 0 5px
        .comments-content
          font-size: 14px
          line-height: 20px
          color: #666666
    .open-app
      text-align: center
      font-size: 14px
      line-height: 46px
*/

.clsTopTip
  position: fixed
  left: 0
  right: 0
  bottom: 60px
  text-align: center
  >>>.top-tip-inner
    display: inline-block
    padding: 0 10px
    box-sizing: border-box
    font-size: 12px
    line-height: 24px
    border-radius: 12px
    background: #A9A9A9
    color: #fff
</style>
